import 'dart:convert';

import 'package:bxultimate/data/request/application_request.dart';
import 'package:bxultimate/domain/application/examination/ExaminationQuestionDto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import 'state.dart';

class ExaminationAnswerCardResultController extends GetxController {
  final ExaminationAnswerCardResultState state =
      ExaminationAnswerCardResultState();


  final examId = Get.arguments;
  final lat = '';
  final lon = '';
  final countyCode ='';
  final time ='';

  TextEditingController inputController = TextEditingController();
  String radioSelected = '';
  var checkBoxSelected = <String>[];

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    join();
  }

  void join() async {
    state.examinationJoinDto = await ApplicationRequest.clickJoinExamination(
        examId, lat, lon, countyCode);


    // 获取题目
    ExaminationQuestionDto question = await ApplicationRequest.getItemByDaanId(
        state.examinationJoinDto.currentId, '',  state.examinationJoinDto.currentId, 'jx');
    updateAnswer(question);
    state.question = question;
  }

  void prev() async {
    if(state.question.preId == null || state.question.preId == ''){
      SmartDialog.showToast('已经是第一题了');
      return;
    }
    // 提交答案
    ExaminationQuestionDto question = await ApplicationRequest.getItemByDaanId(
        state.question.currentId, '', state.question.preId, 'jx');
    updateAnswer(question);
    state.question = question;
  }

  next() async {
    if(state.question.nextId == null || state.question.nextId == ''){
      SmartDialog.showToast('已经是最后一题了');
      return;
    }
    var answer = inputController.text;

    if (state.question.titleType == 1) {
      // 单选
      answer = radioSelected;
    }

    if (state.question.titleType == 2) {
      // 多选
      answer = checkBoxSelected.join("!@#");
    }
    // 提交答案
    ExaminationQuestionDto question = await ApplicationRequest.getItemByDaanId(
        state.question.currentId, answer, state.question.nextId, 'jx');
    updateAnswer(question);
    state.question = question;

    // 更新用户答案
  }

  updateAnswer(question) {
    if (question.titleType == 1) {
      radioSelected = question.userAnswer.toString();
    }
    if (question.titleType == 2) {
      var a = json.decode(json.encode(question.userAnswer));

      for (var e in a) {
        checkBoxSelected.add(e);
      }
    }
    if (question.titleType == 3) {
      inputController.text = json.decode(json.encode(question.userAnswer))[0];
    }
  }

  void redirectQuestion(String? id) async {
    // 提交答案
    state.question = await ApplicationRequest.getItemByDaanId(
        state.question.currentId, '', id, 'jx');
    Get.back();
  }

}
